import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

class LocationList {
  final List<MyLocation> list;

  LocationList({required this.list});

  static Future<LocationList> fromStorage(SharedPreferences? prefs) async {
    if (prefs == null) {
      prefs = await SharedPreferences.getInstance();
    }
    String? json = prefs.getString('location_list');
    LocationList locationList = LocationList(list: []);
    if (json != null) {
      try {
        locationList = LocationList.fromJson(jsonDecode(json));
      } catch(e) {
        print('获取数据异常'+ e.toString());
      }

    }
    return locationList;
  }

  static Future<void> setStorage(MyLocation location) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    LocationList locationList = await fromStorage(prefs);
    locationList.list.add(location);
    prefs.setString('location_list', jsonEncode(locationList.toJson()));
  }

  // JSON 序列化
  List<Map<String, dynamic>> toJson() {
    return list.map((item) => item.toJson()).toList();
  }

  // JSON 反序列化
  factory LocationList.fromJson(List<dynamic> json) => LocationList(
    list: (json as List)
        .map((item) => MyLocation.fromJson(item))
        .toList(),
  );
}

class MyLocation {
  final String title;
  final String? desc;
  final String? image;

  MyLocation({required this.title, this.desc, this.image});

  Map<String, dynamic> toJson() => {
    'title': title ?? '',
    'desc': desc ?? '',
    'image': image ?? '',
  };

  factory MyLocation.fromJson(dynamic json) => MyLocation(
    title: json['title'] as String,
    desc: json['desc'] as String,
    image: json['image'] as String,
  );
}